import Taro, { Component } from '@tarojs/taro'
import { AtInput } from 'taro-ui'
import { View, Text, ScrollView, Image } from '@tarojs/components'
import { ButtonItem, ItemCard, Loading } from '@components'
import { connect } from '@tarojs/redux'
import * as actions from '@actions/order'
import { getWindowHeight } from '@utils/style'
import { setGlobalData, getGlobalData } from '@store/global_data'
import address_b_bg from "@assets/address_b_bg.png";
import './orderSettlement.scss'

@connect(state => state.order, { ...actions })
class OrderSettlement extends Component {
  config = {
    navigationBarTitleText: '确认订单'
  }

  constructor (props) {
    super(props)
    let fromType = this.$router.params.fromType
    let items = []
    if (this.$router.params.items) {
      items = JSON.parse(decodeURIComponent(this.$router.params.items))
    }
    this.state = {
      loading: true,
      disabled: false,
      fromType: fromType,
      items: items,
      addressId: undefined,
      address: {},
      priceInfo: {},
      itemList: [],
      buyerMessage: ''
    }
  }

  componentDidMount() {
    this.loadSettlementInfo()
  }

  componentDidShow() {
    const addressId = getGlobalData('orderSettlement-addressId')
    if (addressId && addressId != 0 && addressId != this.state.addressId) {
      this.loadSettlementInfo(addressId)
      setGlobalData('orderSettlement-addressId', 0)
    }
  }

  loadSettlementInfo(_addressId) {
    let addressId = _addressId || this.state.addressId
    this.props.dispatchOrderSettlement({
      fromType: this.state.fromType,
      items: this.state.items,
      addressId: addressId,
    }).then(data => {
      if (data.address) {
        addressId = data.address.id
      }
      this.setState({
        loading: false,
        address: data.address,
        addressId: addressId,
        priceInfo: data.priceInfo,
        itemList: data.itemList
      })
    })
  }

  handleAddressList = () => {
    const { address } = this.state
    Taro.navigateTo({
      url: '/pages/address/address?id=' + address.id
    })
  }

  handleAddressAdd = () => {
    Taro.navigateTo({
      url: '/pages/addressAdd/addressAdd'
    })
  }

  handleOrder = () => {
    const { itemList = [], addressId, fromType, buyerMessage } = this.state
    const items = []
    itemList.forEach(item => {
      items.push({
        itemId: item.itemId,
        skuId: item.skuId,
        itemNum: item.itemNum
      })
    })

    // 提交订单
    this.props.dispatchOrderSubmit({
      fromType: fromType,
      addressId: addressId,
      items: items,
      buyerMessage: buyerMessage
    }).then(data => {
      // 设置不能再付款
      this.setState({disabled: true})
      // 订单支付
      const orderNo = data.orderNo
      this.props.dispatchOrderPay({orderNo: orderNo}).then( (payData) => {
        Taro.requestPayment(payData.pay).then(res => {
          Taro.navigateTo({
            url: '/pages/payResult/payResult?msg=' + res.errMsg + '&orderNo=' + orderNo + '&payAmount=' + payData.order.payAmount
          })
        }).catch((err) => {
          if ('requestPayment:fail cancel' != err.errMsg) {
            Taro.navigateTo({
              url: '/pages/payResult/payResult?msg=' + err.errMsg + '&orderNo=' + orderNo + '&payAmount=' + payData.order.payAmount
            })
          }
        })
      })
    })
  }


  render () {
    const { itemList = [], address = {}, priceInfo ={} } = this.state
    const canPay = this.state.disabled || !(itemList.length > 0)

    if (this.state.loading) {
      return <Loading />
    }

    const BUTTON = {
      width: Taro.pxTransform(200),
      height: Taro.pxTransform(65),
      borderRadius: Taro.pxTransform(30),
      marginTop: Taro.pxTransform(20),
      marginBottom: Taro.pxTransform(20),
      marginRight: Taro.pxTransform(20)
    }
    const TEXT = {
      fontSize: Taro.pxTransform(28),
      fontWeight: Taro.pxTransform(600),
      letterSpacing: Taro.pxTransform(3)
    }
    return (
      <View className='order-submit'>
        <ScrollView
          scrollY
          className='order-submit__wrap'
          style={{ height: getWindowHeight(false) }}
        >

          <View className='address'>
            <View className='address-wrap'>
              {address
                ?
                <View className='address-info' onClick={this.handleAddressList}>
                  <View className='address-info-t'>
                    <Text className='address-info-name'>{address.consignee}</Text>
                    <Text className='address-info-tel'>{address.phone}</Text>
                    <View className='address-info-icon at-icon at-icon-chevron-right'></View>
                  </View>
                  <View className='address-info-b'>
                    {address.defaulted && <Text className='address-info-tab'>默认</Text>}
                    {address.address}
                  </View>
                </View>
                :
                <View className='address-no' onClick={this.handleAddressAdd}>
                  请添加收货地址
                  {/*<View className='address-no-icon at-icon at-icon-add'></View>*/}
                </View>
              }
            </View>
            <Image className='address-bg' src={address_b_bg} />
          </View>

          <View className='order-submit__list'>
            {itemList.map((item, index) => (
              <ItemCard key={index} item={item} />
            ))}
          </View>

          <View className='message-box'>
            <View className='message-box-item'>
              <Text>配送方式</Text>
              <Text>快递</Text>
            </View>
            <AtInput
              name='message'
              title='买家留言'
              type='text'
              placeholder='留言建议提前协商（50字以内）'
              className='message-input'
              value={this.state.buyerMessage}
            />
          </View>

          <View className='order-submit__price'>
            <View className='order-submit__price-item'>
              <View className='order-submit__price-item-name'>商品金额</View>
              <View className='order-submit__price-item-value'>{'¥' + priceInfo.totalAmount}</View>
            </View>
            <View className='order-submit__price-item'>
              <View className='order-submit__price-item-name'>运费</View>
              <View className='order-submit__price-item-value'>{'+ ¥' + priceInfo.postAmount}</View>
            </View>
          </View>

        </ScrollView>

        <View className='order-submit__footer'>
          <Text className='order-submit__footer-price'>
            {'应付: ¥' + priceInfo.payAmount}
          </Text>
          <View className='order-submit__footer-btn'>
            {canPay ?
              <ButtonItem disabled text='提交订单' compStyle={BUTTON} textStyle={TEXT} />
              :
              <ButtonItem type='primary' text='提交订单' compStyle={BUTTON} textStyle={TEXT} onClick={this.handleOrder} />
            }
          </View>
        </View>

      </View>
    )
  }
}

export default OrderSettlement
